import React, {Component, Image} from 'react';
import logo from './logo.svg';
import './App.css';
import {Form, Input, Checkbox, Button, Menu, Breadcrumb, Icon, Spin, Alert, Table} from 'antd';
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
const FormItem = Form.Item;

import {
    BrowserRouter as Router,
    Route,
    Link,
    Redirect,
    withRouter
} from 'react-router-dom'


class Home extends Component {
    render() {
        return <div>Home</div>
    }
}

const JiaDian = ({routes}) => (
    <div className="ant-layout-wrapper">
        <div className="ant-layout-container">
            <aside className="ant-layout-sider">
                <Menu mode="inline" defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']}>
                    <SubMenu key="sub1" title={<span><Icon type="user"/>电视</span>}>
                        <Menu.Item key="/JiaDian/Hezi"><Link to="/JiaDian/Hezi">合资</Link></Menu.Item>
                        <Menu.Item key="/JiaDian/GuoChang"><Link to="/JiaDian/GuoChang">国产</Link></Menu.Item>
                        <Menu.Item key="3">互联网</Menu.Item>
                    </SubMenu>
                    <SubMenu key="sub2" title={<span><Icon type="laptop"/>空调</span>}>
                        <Menu.Item key="5">柜式</Menu.Item>
                        <Menu.Item key="6">挂式</Menu.Item>
                        <Menu.Item key="7">中央</Menu.Item>
                    </SubMenu>
                    <SubMenu key="sub3" title={<span><Icon type="notification"/>冰箱</span>}>
                        <Menu.Item key="9">多门</Menu.Item>
                        <Menu.Item key="10">双门</Menu.Item>
                        <Menu.Item key="11">对开门</Menu.Item>
                    </SubMenu>
                </Menu>
            </aside>
            <div className="ant-layout-content">
                <div style={{height: 240}}>
                    <div style={{clear: 'both'}}>
                        {routes.map((route, i) => (
                            <RouteWithSubRoutes key={i} {...route} />
                        ))}
                    </div>
                </div>
            </div>
        </div>
        <CopyRight/>
    </div>
);

class FuZhuang extends Component {
    constructor(props) {
        super(props);
        this.state = {
            collapse: false
        }
        this.onCollapseChange = this.onCollapseChange.bind(this)
    }

    onCollapseChange = () => {
        this.setState({collapse: !this.state.collapse})
    }

    render() {
        const routes = this.props.routes;
        return (
            <div className="ant-layout-wrapper">
                <div className="ant-layout-container">
                    <div
                        className={this.state.collapse ? "ant-layout-aside ant-layout-aside-collapse" : "ant-layout-aside"}>
                        <aside className="ant-layout-sider">
                            <Menu mode="inline" theme="dark" defaultSelectedKeys={['user']}>

                                <SubMenu key="sub12"
                                         title={<span><Icon type="user"/><span className="nav-text">男装</span></span>}>
                                    <Menu.Item key="/FuZhuang/YunDong"><Link to="/FuZhuang/YunDong"><span className="nav-text">运动</span></Link></Menu.Item>
                                    <Menu.Item key="12"><span className="nav-text">夹克</span></Menu.Item>
                                </SubMenu>
                                <SubMenu key="sub22"
                                         title={<span><Icon type="laptop"/><span className="nav-text">女装</span></span>}>
                                    <Menu.Item key="15"><span className="nav-text">连衣裙</span></Menu.Item>
                                    <Menu.Item key="16"><span className="nav-text">短裙</span></Menu.Item>
                                    <Menu.Item key="17"><span className="nav-text">舞裙</span></Menu.Item>
                                </SubMenu>
                                <SubMenu key="sub32" title={<span><Icon type="notification"/><span className="nav-text">配饰</span></span>}>
                                    <Menu.Item key="19"><span className="nav-text">太阳镜</span></Menu.Item>
                                    <Menu.Item key="110"><span className="nav-text">手套</span></Menu.Item>
                                    <Menu.Item key="/FuZhuang/WeiJin"><Link to="/FuZhuang/WeiJin"><span className="nav-text">围巾</span></Link></Menu.Item>
                                </SubMenu>

                            </Menu>
                            <div className="ant-aside-action" onClick={this.onCollapseChange}>
                                {this.state.collapse ? <span><Icon type="right"/>展开</span> : <span><Icon type="left"/>收起</span>}
                            </div>
                        </aside>
                    </div>

                        <div className="ant-layout-content">
                            <div style={{height: 440}}>
                                <div style={{clear: 'both'}}>
                                    {routes.map((route, i) => (
                                        <RouteWithSubRoutes key={i} {...route} />
                                    ))}
                                </div>
                            </div>
                        </div>
                </div>
                <CopyRight/>
            </div>
        )
    }
}

const Protected = () => (
    <div className="ant-layout-wrapper">
        <div className="ant-layout-container">
            <div className="ant-layout-content">
                <div style={{height: 240}}>
                    <div style={{clear: 'both'}}>
                        This is a protected page! If you see this, you have super privilege!
                    </div>
                </div>
            </div>
        </div>
        <CopyRight/>
    </div>
);


const dataSource = [{
    key: '1',
    name: '胡彦斌',
    age: 32,
    address: '西湖区湖底公园1号'
}, {
    key: '2',
    name: '胡彦祖',
    age: 42,
    address: '西湖区湖底公园1号'
}];


const HeZi = () => <h3>合资</h3>
const GuoChang = () => <h3>国产</h3>
class YunDong extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            data: [],
        }
    }

    fetchData() {

        fetch('http://localhost:8080/data')
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
                if (responseJson.code === '000000') {
                    this.setState({
                        loading: false,
                        data: responseJson.data,
                    })
                } else {
                    this.setState({loading: false});
                }
            })
            .catch((err) => {
                console.log(err);
            })

    }
    componentDidMount() {
        this.fetchData();
    }

    render() {
        const columns = [{
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            className: 'text-center',
        }, {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            className: 'text-center',
        }, {
            title: '住址',
            dataIndex: 'address',
            key: 'address',
            className: 'text-center',
        }];
        return (
            <Table rowKey={record => record.name} dataSource={this.state.data} columns={columns} bordered loading={this.state.loading}/>
        )
    }
}
const WeiJin = () => <h3>围巾</h3>

class CopyRight extends Component {
    render() {
        return (
            <div className="ant-layout-footer">
                Ant Design 版权所有 © 2015 由蚂蚁金服体验技术部支持
            </div>
        )
    }
}

const fakeAuth = {
    isAuthenticated: window.sessionStorage.getItem('_jsession_token') !== null && window.sessionStorage.getItem('_jsession_token') !== 'null',
    authenticate(values, cb) { // cb means callback
        // TODO send request to server
        fetch('http://localhost:8080/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            body: JSON.stringify(values),
        }).then(
            (response) => response.json()
        ).then(
            (responseJson) => {
                console.log(responseJson);
                if (responseJson.code === '000000') {
                    window.sessionStorage.setItem('_jsession_token',  responseJson.data)
                    fakeAuth.isAuthenticated = true
                } else {
                    console.log(responseJson.msg);
                }
                cb(); // 执行回调
            }
        ).catch((err) => {
            console.log(err);
        });

        // setTimeout(cb, 1000) // 模拟异步
    },
    signout(cb) {
        let param = 'token=' + window.sessionStorage.getItem('_jsession_token');
        console.log(param)
        console.log(fakeAuth.isAuthenticated)
        fetch('http://localhost:8080/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json',
            },
            body: param,
        }).then(
            (response) => response.json()
        ).then(
            (responseJson) => {
                console.log(responseJson);
                if (responseJson.code === '000000') {
                    window.sessionStorage.setItem('_jsession_token',  null)
                    fakeAuth.isAuthenticated = false
                } else {
                    console.log(responseJson.msg);
                }
                if (cb) {
                    cb(); // 执行回调
                }
            }
        ).catch((err) => {
            console.log(err);
        });
    }
}

const AuthButton = withRouter(({ history }) => (
    fakeAuth.isAuthenticated ? (
        <p style={{ color: "white" }}>
            欢迎! <Button onClick={() => {
            fakeAuth.signout(() => history.push('/'))
        }}>登出</Button>
        </p>
    ) : (
        <p style={{ color: "white" }}>欢迎,游客!</p>
    )
))

const PrivateRoute = ({component: Component, ...rest}) => (
    <Route {...rest} render={props => (
        fakeAuth.isAuthenticated ? (
            <Component {...props} />
        ) : (
            <Redirect to={{
                pathname: '/Login',
                state: {from: props.location}
            }}/>
        )
    )}/>
);


class RawLogin extends Component {
    constructor(props) {
        super(props);
        this.state = {
            redirectToReferrer: false,
            processing: false,
            isFirst: true,
        }
        console.log('isFirst: ', this.state.isFirst, ', redirectToReferrer: ', this.state.redirectToReferrer);
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                // TODO Submit To Server, execute Login Action
                this.login(values);
            }
        });
    }

    login = (values) => {
        this.setState({processing: true, isFirst: false})
        fakeAuth.authenticate(values, () => {
            let token = window.sessionStorage.getItem("_jsession_token");
            console.log('token: ', token);
            this.setState({redirectToReferrer: token!==null && token !== 'null', processing: false})

        })
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const {from} = this.props.location.state || {from: {pathname: '/'}}
        const {redirectToReferrer, processing} = this.state

        if (redirectToReferrer) {
            return (
                <Redirect to={from}/>
            )
        }
        return (
            <Form onSubmit={this.handleSubmit} className="login-form">
                <FormItem>
                    {getFieldDecorator('userName', {
                        rules: [{required: true, message: '请输入用户名'}],
                    })(
                        <Input prefix={<Icon type="user" style={{fontSize: 13}}/>} placeholder="用户名"/>
                    )}
                </FormItem>
                <FormItem>
                    {getFieldDecorator('password', {
                        rules: [{required: true, message: '请输入密码'}],
                    })(
                        <Input prefix={<Icon type="lock" style={{fontSize: 13}}/>} type="password" placeholder="密码"/>
                    )}
                </FormItem>
                <FormItem>
                    {getFieldDecorator('remember', {
                        valuePropName: 'checked',
                        initialValue: true,
                    })(
                        <Checkbox>记住我</Checkbox>
                    )}
                    <Button type="primary" htmlType="submit" className="login-form-button">登录</Button>
                </FormItem>
                <Spin spinning={this.state.processing} tip="正在登录" size="large"></Spin>
                {
                    !this.state.isFirst && !this.state.redirectToReferrer ? <span><Alert type="error" message="登录失败, 用户名或密码不正确" /></span> : <span></span>
                }
            </Form>
        )
    }

}

const Login = Form.create()(RawLogin);

// 在这里定义路由的配置
// 注意细节: path以斜杠开头
const routes = [
    {
        path: '/JiaDian',
        component: JiaDian,
        routes: [
            {
                path: '/JiaDian/Hezi',
                component: HeZi
            }, {
                path: '/JiaDian/GuoChang',
                component: GuoChang
            }
        ]
    }, {
        path: '/FuZhuang',
        component: FuZhuang,
        routes: [
            {
                path: '/FuZhuang/YunDong',
                component: YunDong
            }, {
                path: '/FuZhuang/WeiJin',
                component: WeiJin
            }
        ]
    }, {
        path: '/Protected',
        component: Protected,
    }, {
        path: '/Login',
        component: Login
    }
];

// 把 <Route> 组件像这样包一层，然后在需要使用 <Route> 的地方使用 <RouteWithSubRoutes>
// 自路由可以加到任意路由组件上。
// 注意细节,props不用括号括起来
const RouteWithSubRoutes = (route) => (
    <Route path={route.path} render={props => (
        // 把自路由向下传递来达到嵌套
        <route.component {...props} routes={route.routes}/>
    )}/>
);


class App extends Component {
    render() {
        return (
            <Router>
                <div className="ant-layout-topaside">
                    <div className="ant-layout-header">
                        <div className="ant-layout-wrapper">
                            <div className="ant-layout-loginout">
                                <AuthButton/>
                            </div>
                            <div className="ant-layout-logo"></div>
                            <Menu theme="dark" mode="horizontal"
                                  defaultSelectedKeys={['JiaDia']} style={{lineHeight: '64px'}}>
                                <Menu.Item key="JiaDian"><Link to="/JiaDian">家用电器</Link></Menu.Item>
                                <Menu.Item key="FuZhuang"><Link to="/FuZhuang">服装服饰</Link></Menu.Item>
                                <Menu.Item key="Protected"><Link to="/Protected">受保护页面</Link></Menu.Item>
                            </Menu>

                            <PrivateRoute path="/Protected" component={Protected}/>
                        </div>
                    </div>

                    {routes.map((route, i) => (
                        <RouteWithSubRoutes key={i} {...route} />
                    ))}

                </div>
            </Router>
        );
    }
}


export default App;
